package com.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@Controller
@RequestMapping("/api/read")
public class MessageReadController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private MessageReadService messageReadService;

    @PostMapping("/insertRead")//    新增/修改已读
    public Result<Object> insertRead(
            @RequestBody JSONObject json,
            HttpServletRequest request) {
        Integer id = Integer.valueOf(json.get("id").toString());

        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        MessageReadModel readModel = new MessageReadModel();
        if (user.getRoles() != 1) {
            readModel.setPersonId(user.getPersonId());
        } else {
            readModel.setPersonId(user.getDepartmentId());
        }
        readModel.setMessageId(id);
        readModel.setCreateTime(CommonHelp.getNowTimestamp());
        MessageReadModel readModel1;
        if (user.getDepartmentId() == 1) {
            readModel1 = messageReadService.getReadByReadId(id, user.getDepartmentId());
        } else {
            readModel1 = messageReadService.getReadByReadId(id, user.getPersonId());
        }
        if (readModel1 != null) {
            return Result.success(null);
        } else {
            messageReadService.insert(readModel);
            return Result.success(null);
        }

    }
}
